<?php
namespace  app\components;

class Main {

    /**
     * 遍历获取目录下的指定类型的文件
     */
    public function getfiles($path, &$files = array()) {
        if (!is_dir($path)) return null;
        $handle = opendir($path);
        while (false !== ($file = readdir($handle))) {
            if ($file != '.' && $file != '..') {
                $path2 = $path . '/' . $file;
                if (is_dir($path2)) {
                    Main::getfiles($path2, $files);
                } else {
//                    if (preg_match("/\Controller/i", $file)) {
                    $files[] = $path2;
//                    }
                }
            }
        }
        return $files;
    }
    //从 $words 字符串中 截取前 $num 个单词
    // functioned by PHP designer Hiosiao,
    function subWords($words, $num, $end = '') {
        $words = trim($words);
        $total_num = str_word_count($words); // 获取$words 中单词个数
        if ($total_num == 1) return substr($words, 0, $num) . $end;
        if ($total_num <= $num) { // 如果$words 中单词个数少于 $num
            return $words;
        } else {
            $pattern = '/([\S]+?[ ]+){' . $num . '}/';
            preg_match($pattern, $words, $out);
            $res = @$out[0] . $end; //如果字符串过长，将以 ... 结束
            return trim($res);
        }
    }
    //二维数组根据某个键排序 $keys
    public function arraySort($arr, $keys, $type = 'asc') {
        $keysvalue = $new_array = array();
        foreach ($arr as $k => $v) {
            $keysvalue[$k] = $v[$keys];
        }
        if ($type == 'asc') {
            asort($keysvalue);
        } else {
            arsort($keysvalue);
        }
        reset($keysvalue);
        foreach ($keysvalue as $k => $v) {
            $new_array[$k] = $arr[$k];
        }
        return $new_array;
    }

    /*
     * user agent
     * */
    //取得用户身份标识
    public static function userAgent($par = 'ETH') {
        $ag = @$_SERVER['HTTP_USER_AGENT'] . $_SERVER['SERVER_ADDR'] . $par;
        return md5($ag);
    }

    /*取得操作系统*/
    public function getOs($os = '') {
        if (!($os)) {
            $os = $_SERVER['HTTP_USER_AGENT'];
        }
        $agent = strtolower($os);
        $os = '';
        if (strpos($agent, 'win') !== false) {
            if (strpos($agent, 'nt 5.1') !== false) {
                $os = 'Windows XP';
            } elseif (strpos($agent, 'nt 5.2') !== false) {
                $os = 'Windows 2003';
            } elseif (strpos($agent, 'nt 5.0') !== false) {
                $os = 'Windows 2000';
            } elseif (strpos($agent, 'nt 6.0') !== false) {
                $os = 'Windows Vista';
            } elseif (strpos($agent, 'nt') !== false) {
                $os = 'Windows NT';
            } elseif (strpos($agent, 'win 9x') !== false && strpos($agent, '4.90') !== false) {
                $os = 'Windows ME';
            } elseif (strpos($agent, '98') !== false) {
                $os = 'Windows 98';
            } elseif (strpos($agent, '95') !== false) {
                $os = 'Windows 95';
            } elseif (strpos($agent, '32') !== false) {
                $os = 'Windows 32';
            } elseif (strpos($agent, 'ce') !== false) {
                $os = 'Windows CE';
            } else {
                $os = 'Windows';
            }
        } elseif (strpos($agent, 'linux') !== false) {
            $os = 'Linux';
        } elseif (strpos($agent, 'unix') !== false) {
            $os = 'Unix';
        } elseif (strpos($agent, 'sun') !== false) {
            $os = 'SunOS';
        } elseif (strpos($agent, 'ibm') !== false) {
            $os = 'IBM OS/2';
        } elseif (strpos($agent, 'mac') !== false) {
            $os = 'Macintosh';
        } elseif (strpos($agent, 'compatible') !== false) {
            $os = 'Windows';
        } elseif (strpos($agent, 'powerpc') !== false) {
            $os = 'PowerPC';
        } elseif (strpos($agent, 'aix') !== false) {
            $os = 'AIX';
        } elseif (strpos($agent, 'hpux') !== false) {
            $os = 'HPUX';
        } elseif (strpos($agent, 'netbsd') !== false) {
            $os = 'NetBSD';
        } elseif (strpos($agent, 'bsd') !== false) {
            $os = 'BSD';
        } elseif (strpos($agent, 'osf1') !== false) {
            $os = 'OSF1';
        } elseif (strpos($agent, 'irix') !== false) {
            $os = 'IRIX';
        } elseif (strpos($agent, 'freebsd') !== false) {
            $os = 'FreeBSD';
        } elseif (strpos($agent, 'teleport') !== false) {
            $os = 'teleport';
        } elseif (strpos($agent, 'flashget') !== false) {
            $os = 'flashget';
        } elseif (strpos($agent, 'webzip') !== false) {
            $os = 'webzip';
        } elseif (strpos($agent, 'offline') !== false) {
            $os = 'offline';
        } elseif (strpos($agent, 'android') !== false) {
            $os = 'android';
        } elseif (strpos($agent, 'iphone') !== false) {
            $os = 'iphone';
        } elseif (strpos($agent, 'ipad') !== false) {
            $os = 'ipad';
        } elseif (strpos($agent, 'blackberry') !== false) {
            $os = 'blackberry';
        } elseif (strpos($agent, 'googlebot') !== false) {
            $os = 'googlebot';
        } elseif (strpos($agent, 'yahoo') !== false) {
            $os = 'yahoo';
        } elseif (strpos($agent, 'bingbot') !== false) {
            $os = 'bingbot';
        } else {
            $os = $agent;
        }
        return strtolower($os);
    }

    /*
     * 密码加密
     * */
    public function mymd5($str, $length = 10, $param = '!%#$%#$%$^#') {
        return substr(md5(md5($str . $param)) , 10, $length);
    }

    /*
     * 图片绝对路径
     * */
    public static function imageUrl($url, $path = false) {
        //var_dump('before',$url);
        if(!preg_match('/upload/',$url))
            return $url;
        $url = preg_replace("#.*upload#", "/upload", $url);
        //var_dump($url);
        if ($path) return ROOT_PATH . $url;
        return Yii::app()->baseUrl . $url;
    }
    /*
     * is image
     * */
    public static function isImage($url) {
        if (!file_exists(Main::imageUrl($url, true))) return false;
        if (preg_match("#jpg|png|gif#", $url)) return true;
        else return false;
    }
    /*
     * 文章内容图片路径转换
     * */
    public function contentImageUrl($content) {
        $content = preg_replace_callback('/<img([^>]*)src\s*=\s*"([^>"]*\.(?:png|jpg|bmp|gif))"([^>]*)>/', 'Main::contentImageUrlCallBack', $content);
        return $content;
    }
    public static function contentImageUrlCallBack($m, $layz = false) {

        $src = "http://" . $_SERVER['HTTP_HOST'].Main::imageUrl($m[2]);

        if ($layz) {
            $lay = Yii::app()->getController()->frontUrl . '/images/default.jpg';
            return '<img src="' . $lay . '" ' . $m[1] . ' ' . $m[3] . ' data-original="' . $src . '" />';
        }
        return '<img src="' . $src . '" ' . $m[1] . ' ' . $m[3] . '>';
    }

    //防注入函数
    public function escape($str) {
        $str = preg_replace("/<|>|select|inert|update|delete|\'|\/\*|\*|\.\.\/|\.\/|UNION|into|load_file|outfile/i", "", $str);
        return $str;
    }
    /*
     * 数量选择限制
     * */
    public function numberData($start = 0, $end = 100) {
        return array_combine(range($start, $end) , range($start, $end));
    }
    /*取得时间段的开始 和 结束
     * @param string $type (week-周,year-年,sea-季度,day-天)
     * @param int    $n    (-1，0，+1 当周/年/季度/天)
     * @param string $format (可选的格式化时间，默认返回 时间戳)
     *
     * */
    public static function getDurDate($type = 'week', $n = 0, $format = '') {
        $date = array();
        if ($type == 'week') {
            $date['start'] = mktime(0, 0, 0, date("m") , date("d") - date("w") + 1, date("Y"));
            $date['end'] = mktime(23, 59, 59, date("m") , date("d") - date("w") + 7, date("Y"));
        }
        elseif ($type == 'days7') {  /*前7天*/
            $date['start'] = mktime(0, 0, 0, date("m") , date("d")-7+$n, date("Y"));
            $date['end'] = mktime(23, 59, 59, date("m") , date("d")+$n , date("Y"));
        }
        elseif ($type == 'mon') {
            $date['start'] = mktime(0, 0, 0, date("m") + $n, 1, date("Y"));
            $date['end'] = mktime(23, 59, 59, date("m") + $n, date("t") , date("Y"));
        } elseif ($type == 'sea') {
            $getMonthDays = date("t", mktime(0, 0, 0, date('n') + (date('n') - 1) % 3, 1, date("Y")));
            $date['start'] = mktime(0, 0, 0, date('n') - (date('n') - 1) % 3, 1, date('Y'));
            $date['end'] = mktime(23, 59, 59, date('n') + (date('n') - 1) % 3, $getMonthDays, date('Y'));
        } elseif ($type == 'year') {
            $date['start'] = mktime(0, 0, 0, 1, 1, date("Y") + $n);
            $date['end'] = mktime(23, 59, 59, 12, 31, date("Y") + $n);
        } elseif ($type == 'day') {
            $date['start'] = mktime(0, 0, 0, date("m") , date("d") , date("Y"));
            $date['end'] = mktime(23, 59, 59, date("m") , date("d") , date("Y"));
        }
        if ($format) {
            $date['start'] = date($format, $date['start']);
            $date['end'] = date($format, $date['end']);
        }
        return $date;
    }
    /*
     * 取得某年内每一周起始
     * */
    function getDurWeek($year) {
        $year_start = $year . "-01-01";
        $year_end = $year . "-12-31";
        $startday = strtotime($year_start);
        if (intval(date('N', $startday)) != '1') {
            $startday = strtotime("next monday", strtotime($year_start)); //获取年第一周的日期
        }
        $year_mondy = date("Y-m-d", $startday); //获取年第一周的日期

        $endday = strtotime($year_end);
        if (intval(date('W', $endday)) == '7') {
            $endday = strtotime("last sunday", strtotime($year_end));
        }

        $num = intval(date('W', $endday));
        for ($i = 1; $i <= $num; $i++) {
            $j = $i -1;
            $start_date = date("Y-m-d", strtotime("$year_mondy $j week "));

            $end_day = date("Y-m-d", strtotime("$start_date +6 day"));

            $week_array[$i] = array ($start_date, $end_day);
        }
        return $week_array;
    }
    //取得时间段内每一天
    public static function during($week, $format = '') {
        $start = $week['start'];
        $end = $week['end'];
        $day_num = ceil(($end - $start) / (24 * 3600));
        $days = array();
        $day = array();
        for ($i = 0; $i < $day_num; $i++) {
            $per_day = ((24 * 3600) * $i);
            $day_start = strtotime(date("Y-m-d", $start)) + $per_day;
            $day_end = $day_start + (23 * 3600 + 3599);
            if ($format) {
                $day_start = date($format, $day_start);
                $day_end = date($format, $day_end);
            }
            $day['start'] = $day_start;
            $day['end'] = $day_end;
            $days[] = $day;
        }
        return $days;
    }
    /*
     * 取得开始时间和结束时间
     * res 1-查询结束时间不能小于开始时间
     * res 2-时间转换为时间戳错误
     * */
    public static function mstrToTime($arr = array()) {
        $start = @strtotime($arr[0]);
        $end = @strtotime($arr[1]);
        if ($end < $start) return 1;
        if (!$start || !$end) return 2;
        if ($start == $end) {
            preg_match("/^(\d{4})(\d{2})(\d{2})/", $arr[1], $sr);
            $end = @mktime(23, 59, 59, $sr[2], $sr[3], $sr[1]);
        }
        $res['start'] = $start;
        $res['end'] = $end;
        return $res;
    }
    //csv读取
    public static function getCsv($file_name, $start, $end) {
        $file_name = Main::imageUrl($file_name, true);
        $n = 0;
        $lines = array();
        $f = fopen($file_name, "r");
        if ($f) {
            while (!feof($f)) {
                ++$n;
                $line = fgetcsv($f);
                if (!is_array($line)) continue;
                foreach ($line as $key => $val) {
                    $v = iconv('gb2312', 'utf-8', $val);
                    $v = $v ? $v : $val;
                    $line[$key] = $v;
                }
                if ($start <= $n) {
                    $lines[] = $line;
                }
                if ($end == $n) break;
            }
            fclose($f);
        }
        return $lines;
    }
    /*
     * unique words
     * */
    public function uniqueWords($str = "") {
        $str = preg_replace("/  /", " ", strtolower($str));
        $sp = preg_split("/ /", $str);
        $arr = array();
        foreach ($sp as $key => $val) {
            if (trim($val)) $arr[] = $val;
        }
        $arr = array_unique($arr);
        return join($arr, " ");
    }
    /*
     * build pager
     * */
    public function buildPager($count = 0, $size = 10, $url = '') {
        $amount = ceil($count / $size);
        $urls = array();
        for ($i = 0; $i < $amount; $i++) {
            $urls[] = $url . "?page=$i";
        }
        print_r($count);
        die();
    }
    /*
     * 模拟定时任务
     * 当返回1时，定时器已经生效
     * */
    public function cronTab($time = 3600, $s = '') {
        $name = 'cronTab' . $s;
        $n = Yii::app()->cache->get($name);
        $n = intval($n) + 1;
        Yii::app()->cache->set($name, $n, $time);
        return Yii::app()->cache->get($name);
    }
    /**
     * 自动更新显示
     * 商品，文章，评论
     *
     */
    public function autoShow($type = 'article', $id = 0) {
        $params = array(
            'goods' => 3600 * 24 * 5,
            'article' => 3600 * 24 * 9,
            'review' => 3600 * 24 * 1
        );
        $m = Main::cronTab($params[$type], $type);
        if ($type == 'article' && $m === 2) {
            $model = Article::model()->find("is_show=0");
            $model->is_show = 1;
            $model->add_time = time();
            $model->update();
        }
        if ($type == 'goods' && $m === 2) {
            $model = Goods::model()->find("is_show=0");
            $model->is_show = 1;
            $model->add_time = time();
            $model->update();
        }
        if ($type == 'review' && $m === 2) {
            $t = strtotime("-1 years");
            $model = Review::model()->find("add_time< $t");
            $model->id = $id;
            $model->add_time = time();
            $model->update();
        }
    }



    /*
     * api code init
     * */
    public static function apiCodeInit($status = 0) {
        if ($status) $res['status'] = array(
            'errorcode' => 'OK',
            "errorinfo" => ""
        );
        else $res['status'] = array(
            'errorcode' => 'ERROR',
            "errorinfo" => "some error"
        );
        $res['data'] = array();
        return $res;
    }
    /**
     * byte单位转化
     *
     *
     */
    public static function GetByteSize($bytesize) {
        $i = 0;
        //当$bytesize 大于是1024字节时，开始循环，当循环到第4次时跳出；
        while (abs($bytesize) >= 1024) {
            $bytesize = $bytesize / 1024;
            $i++;
            if ($i == 4) break;
        }
        //将Bytes,KB,MB,GB,TB定义成一维数组；
        $units = array(
            "Bytes",
            "KB",
            "MB",
            "GB",
            "TB"
        );
        $newsize = round($bytesize, 2);
        return ("$newsize $units[$i]");
    }
    /*
     * 取得useragent
     * */

    public function userAgens(){
        $mobile = array(
            'Mozilla/5.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) AppleWebKit/600.1.3 (KHTML, like Gecko) Version/8.0 Mobile/12A4345d Safari/600.1.4',
            'Mozilla/5.0 (iPhone; CPU iPhone OS 7_0 like Mac OS X; zh-cn) AppleWebKit/537.51.1 (KHTML, like Gecko) Version/7.0 Mobile/11A465 Safari/9537.53',
            'Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_2_1 like Mac OS X; zh-cn) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8C148 Safari/6533.18.5',
            'Mozilla/5.0 (Linux; Android 4.3; Nexus 10 Build/JSS15Q) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2307.2 Mobile Safari/537.36',
            'Mozilla/5.0 (PlayBook; U; RIM Tablet OS 2.1.0; en-US) AppleWebKit/536.2+ (KHTML like Gecko) Version/7.2.1.0 Safari/536.2+',
            'Mozilla/5.0 (Linux; Android 4.3; Nexus 10 Build/JSS15Q) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2307.2 Safari/537.36',
            'Mozilla/5.0 (Linux; U; Android 4.4.2; en-us; LGMS323 Build/KOT49I.MS32310c) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/30.0.1599.103 Mobile Safari/537.36',
            'Mozilla/5.0 (Linux; U; Android 4.3; en-us; SM-N900T Build/JSS15J) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30',
            'Mozilla/5.0 (Linux; Android 4.4.4; HM NOTE 1LTE Build/KTU84P) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/33.0.0.0 Mobile Safari/537.36 LieBaoFast/3.0.9',
            'Mozilla/5.0 (iPad; CPU OS 7_0 like Mac OS X) AppleWebKit/537.51.1 (KHTML, like Gecko) Version/7.0 Mobile/11A465 Safari/9537.53',
            'Mozilla/5.0 (iPad; CPU OS 4_3_5 like Mac OS X; zh-cn) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8L1 Safari/6533.18.5',


        );
        $desk = array(
            'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:39.0) Gecko/20100101 Firefox/39.0',
            'Windows / Chrome 34: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.137 Safari/537.36',

        );

        return array('mobile'=>$mobile,'desk'=>$desk);
    }
    /**
     * 以不同的useragent file_get_contents
     *
     */
    public static function curl2($url, $userAgent = '',$cookieFile='',$proxy=false) {
        $url = preg_replace("/&amp;/", "&", $url);

        $uas = Main::userAgens();
        $ua = array_merge($uas['mobile'],$uas['desk']);
        $k = array_rand($ua);
        $u = $userAgent ? $userAgent : $ua[$k];
        $ch = curl_init();
        $cache = \Yii::$app->cache;
        $proxylist = $cache['proxylist'];

        if($proxy && $proxylist)
        {
            $r = rand(0,10);
            $p =  $proxylist[$r];
            curl_setopt ($ch, CURLOPT_PROXY, $p['url']);
//            var_dump( $p);

        }

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);
        curl_setopt($ch, CURLOPT_USERAGENT, $u);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        if($cookieFile)
        {

            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);
            curl_setopt($ch, CURLOPT_COOKIEFILE, $cookieFile);
        }


        $r = curl_exec($ch);
        curl_close($ch);


        return $r;
    }
    /*
     * 发送post数据
     * */

    public function post2($url, $post_data = '', $timeout = 5){//curl
         $post_data = http_build_query($post_data);


        $ch = curl_init();

        curl_setopt ($ch, CURLOPT_URL, $url);

        curl_setopt ($ch, CURLOPT_POST, 1);

        if($post_data != ''){

            curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);

        }

        curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_TIMEOUT, 4);


        curl_setopt($ch, CURLOPT_HEADER, false);

        $file_contents = curl_exec($ch);

        curl_close($ch);

        return $file_contents;

    }
    /**
     * Socket版本
     * 使用方法：
     * $post_string = "app=socket&version=beta";
     * request_by_socket('chajia8.com', '/restServer.php', $post_string);
     */
    function postBysocket($remote_server,$remote_path,$post_string,$port = 80,$timeout = 30) {
        $socket = fsockopen($remote_server, $port, $errno, $errstr, $timeout);
        if (!$socket) die("$errstr($errno)");
        fwrite($socket, "POST $remote_path HTTP/1.0");
        fwrite($socket, "User-Agent: Socket Example");
        fwrite($socket, "HOST: $remote_server");
        fwrite($socket, "Content-type: application/x-www-form-urlencoded");
        fwrite($socket, "Content-length: " . (strlen($post_string) + 8) . "");
        fwrite($socket, "Accept:*/*");
        fwrite($socket, "");
        fwrite($socket, "mypost=$post_string");
        fwrite($socket, "");
        $header = "";
        while ($str = trim(fgets($socket, 4096))) {
            $header .= $str;
        }

        $data = "";
        while (!feof($socket)) {
            $data .= fgets($socket, 4096);
        }

        return $data;
    }

    /**
     * 取得代理列表
     */
    public static function getProxyList($page=1){

        $url = "http://www.xicidaili.com/nn/$page";
        $info = Main::curl2($url,'','',false);
        preg_match_all("#<tr class=\"[^\"]*\">[\s\S]+?<td>(\d+\.\d+.\d+.\d+)</td>[\s\S]+?<td>(\d{2,4})</td>[\s\S]+?>([^>]+)</a>[\s\S]+?title=\"([^\"]+)秒#",$info,$arr);
        if(count($arr[1])<2)
            return;

        $res = array();
        foreach($arr[1] as $key=>$val)
        {
            $v['ip'] = $val;
            $v['port'] = $arr[2][$key];
            $v['area'] = $arr[3][$key];
            $v['time'] = $arr[4][$key]*1;
            $v['url'] = 'http://'.$v['ip'].':'.$v['port'];
//            var_dump(get_headers($v['url']));
            $res[] = $v;
        }
        $res=Main::arraySort($res,'time');
        $new = array();
        foreach($res as $k=>$v)
        {
            $new[] = $v;
        }
        var_dump($new);
        Yii::app()->cache->set('proxylist', $new, 60*60*10);
        return $new;
    }
    /**
     * 用shell获取远程文件
     *
     * $file_url    string  文件地址
     * $dir         string  文件存放地址 默认是/tmp/image/
     */
    public static function getFileByWget($url, $dir = '/tmp/image/') {
        if (empty($url)) {
            return null;
        }
        $file_name = $dir . md5(time() . rand());
        $commod = "wget -q {$url} -O {$file_name}";
        system($commod);
        $result = @file_get_contents($file_name);
        return $result;
    }

    /*
     * 解析m3u8
     * */
    public static function m3u8ShellParse($url) {
        $out = $status = '';
        exec("phantomjs " . dirname(__FILE__) . "/server.js $url", $out, $status);
        $res = join("", $out);
        if (preg_match('/iqiyi/', $url)) $m3u8 = Main::getIqiyi($res);
        if (preg_match('/sohu/', $url)) $m3u8 = Main::getSohu($res);
        if (preg_match('/hunantv/', $url)) $m3u8 = Main::getHunantv($res);
        if ($m3u8) Yii::app()->cache->set($url, $m3u8);
        return $m3u8;
    }

    /*
     * @param int $level   1流畅 标清 2高清 3超清 4 1080p
     * @param int $ts      4流畅 1标准 2高强 3 超清
     * */

    public static function getDataFromLiebao($url,$data,$site)
    {

        $uas = Main::userAgens();
        $k = array_rand($uas['mobile']);
        $ua = $uas['mobile'][$k];

        $u = 'http://i.m.liebao.cn/videoparse/videoparse2.php';
        $data = array(
            'data' =>CJSON::encode($data),
            'web_site' => $site,
            'method' => 'getprotourl'
        );
        $fields_string = http_build_query ( $data, '&' );
        $ch = curl_init();
//        curl_setopt ($ch, CURLOPT_PROXY, $proxylist[0]['url']);

        curl_setopt($ch, CURLOPT_URL, $u);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/x-www-form-urlencoded',
            "User-Agent: $ua",
//            'Cookie: Hm_lvt_507a1673dcdcecb62f9554291e6d63fc=1435656971;',
            'Accept: text/html',
            'Connection: Keep-Alive'
        ));
        curl_setopt ( $ch ,  CURLOPT_POST ,  1 );
        curl_setopt ( $ch ,  CURLOPT_POSTFIELDS ,  $fields_string );

        //curl_setopt($ch, CURLOPT_COOKIE, 'QC006=5427a6abc2e76cc59a603b3925baadfe; redpoint_nav_vip=R1; redpoint_channelList=R1; QC112=7ac99ccb563c3089aa93a0e11023aa55; T00404=be57119e333614e258a0ad5b18d28dc2; QC007=https%3A%2F%2Fm.baidu.com%2Fs%3Ffrom%3D1010888o%26word%3D%25E5%25A5%2594%25E8%25B7%2591%25E5%2590%25A7%25E5%2585%2584%25E5%25BC%259F%25E7%25AC%25AC%25E4%25BA%258C%25E5%25AD%25A3');
        ob_start();//开启输出缓冲
        $r = curl_exec($ch);
        $result = ob_get_contents();//得到缓冲区输出的内容，赋给变量$phpinfo
        ob_clean();
        curl_close($ch);

        $result = CJSON::decode($result);
        return $result;

    }
    public static function getIqiyi($url,$data,$level) {
        if($level==1)
            $ts = 4;
        if($level==2)
            $ts = 1;
        if($level==3)
            $ts = 2;
        if($level==4)
            $ts = 3;

        $data = CJSON::decode($data);
        $data['playurl'] = $url;

        $result = Main::getDataFromLiebao($url,$data,'iqiyi');
        $rdata = $result['data'];
        $rheader = $rdata['headers'];


        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $rdata['url']);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-type: text/json',
            'User-Agent:'.$rheader['User-Agent'].'',
            'sign:'.$rheader['sign'].'',
            't:'.$rheader['t'].'',

        ));
        //curl_setopt($ch, CURLOPT_COOKIE, 'QC006=5427a6abc2e76cc59a603b3925baadfe; redpoint_nav_vip=R1; redpoint_channelList=R1; QC112=7ac99ccb563c3089aa93a0e11023aa55; T00404=be57119e333614e258a0ad5b18d28dc2; QC007=https%3A%2F%2Fm.baidu.com%2Fs%3Ffrom%3D1010888o%26word%3D%25E5%25A5%2594%25E8%25B7%2591%25E5%2590%25A7%25E5%2585%2584%25E5%25BC%259F%25E7%25AC%25AC%25E4%25BA%258C%25E5%25AD%25A3');
        ob_start();//开启输出缓冲
        $r = curl_exec($ch);
        $res = ob_get_contents();//得到缓冲区输出的内容，赋给变量$phpinfo
        ob_clean();
        curl_close($ch);
        $res = CJSON::decode($res);
        $tvres =$res['tv']['0']['res'];
        //var_dump($res['tv']['0']);die();
        $tvurl = Main::getIqyiTs($tvres,$ts);

        $m3u8 = @Main::curl2($tvurl) ? @Main::curl2($tvurl) :  @Main::curl2($res['tv']['0']['vid']);

        return $m3u8;

    }
    /*
     * @param int $level   1流畅 标清 2高清 3超清 4 1080p
     * @param int $ts      4流畅 1标准 2高强 3 超清
     * */
    private static function getIqyiTs($res,$ts=3){

        if($ts<1)
            return;
        $m = '';
        foreach($res as $key=>$val)
        {
            if($val['t']=="TS$ts")
            {
                $m = $val['vid'];

            }


        }
        //var_dump($m,$ts);die();
        if(!$m)
        {
            $ts--;
            return Main::getIqyiTs($res,$ts);
        }
        return $m;


    }
    /*
    * @param int $level   1流畅 标清 2高清 3超清 4 1080p
    * @param int $ts      4流畅 1标准 2高强 3 超清
    * */
    public static function getLetv($url,$data,$level) {


        $data = CJSON::decode($data);
        $data['playurl'] = $url.'?ref=liebao&from=ajax';
        $u = 'http://i.m.liebao.cn/videoparse/videoparse2.php';

        $result = Main::getDataFromLiebao($url,$data,'letv');


        $rdata = $result['data'];
        $rheader = $rdata['headers'];


        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $rdata['url']);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-type: text/json',
            'User-Agent:'.$rheader['User-Agent'].'',
//            'sign:'.$rheader['sign'].'',
//            't:'.$rheader['t'].'',

        ));
        //curl_setopt($ch, CURLOPT_COOKIE, 'QC006=5427a6abc2e76cc59a603b3925baadfe; redpoint_nav_vip=R1; redpoint_channelList=R1; QC112=7ac99ccb563c3089aa93a0e11023aa55; T00404=be57119e333614e258a0ad5b18d28dc2; QC007=https%3A%2F%2Fm.baidu.com%2Fs%3Ffrom%3D1010888o%26word%3D%25E5%25A5%2594%25E8%25B7%2591%25E5%2590%25A7%25E5%2585%2584%25E5%25BC%259F%25E7%25AC%25AC%25E4%25BA%258C%25E5%25AD%25A3');
        ob_start();//开启输出缓冲
        $r = curl_exec($ch);
        $res = ob_get_contents();//得到缓冲区输出的内容，赋给变量$phpinfo
        ob_clean();
        curl_close($ch);
        $res = CJSON::decode($res);
        if($level==1)
            $key = 'mp4_180';
        if($level==2)
            $key = 'mp4_350';
        if($level==3)
            $key = 'mp4_1000';
        if($level==4)
            $key = 'mp4_1300';
        $tvurl = @$res['body']['videofile']['infos'][$key];
        $tvurl = $tvurl ? $tvurl : @current($res['body']['videofile']['infos']);
//        var_dump($tvurl);die();
        $tvurl = $tvurl['mainUrl'];
//        var_dump($tvurl);die();
        $rm3u8 = @CJSON::decode(Main::curl2($tvurl)) ;
//        var_dump($rm3u8);die();
        $m3u8  = Main::curl2($rm3u8['location']);

        return $m3u8;

    }
    /*
    * @param int $level   1流畅 标清 2高清 3超清 4 1080p
    * @param int $ts      4流畅 1标准 2高强 3 超清
    * */
    public static function getYouku($url,$data,$level) {
        preg_match("#id_(.+)\.html#",$url,$arr);
        $id = @$arr[1];
        $data = array('vid'=>$id,'playurl'=>$url);
        $result = Main::getDataFromLiebao($url,$data,'youku');

        $rdata = $result['data'];
        $rheader = $rdata['headers'];

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $rdata['url']);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-type: text/json',
            'User-Agent:'.$rheader['User-Agent'].'',
//            'sign:'.$rheader['sign'].'',
//            't:'.$rheader['t'].'',

        ));
        //curl_setopt($ch, CURLOPT_COOKIE, 'QC006=5427a6abc2e76cc59a603b3925baadfe; redpoint_nav_vip=R1; redpoint_channelList=R1; QC112=7ac99ccb563c3089aa93a0e11023aa55; T00404=be57119e333614e258a0ad5b18d28dc2; QC007=https%3A%2F%2Fm.baidu.com%2Fs%3Ffrom%3D1010888o%26word%3D%25E5%25A5%2594%25E8%25B7%2591%25E5%2590%25A7%25E5%2585%2584%25E5%25BC%259F%25E7%25AC%25AC%25E4%25BA%258C%25E5%25AD%25A3');
        ob_start();//开启输出缓冲
        $r = curl_exec($ch);
        $res = ob_get_contents();//得到缓冲区输出的内容，赋给变量$phpinfo
        ob_clean();
        curl_close($ch);



        //解析视频
        $u = 'http://i.m.liebao.cn/videoparse/videoparse2.php';
        $data = array('data'=>$res,'did'=>$rdata['did']);
        $data = array(
            'data' =>CJSON::encode($data),
            'from'=>'ios',
            'web_site' => 'youku',
            'method' => 'decodedata',
            'deviceModel'=>'iPhone7,2',
//            'udid'=>'020000000000|74f8464fe4571f88adf2a38379a2aec99b38a5c9'
        );

        $fields_string = http_build_query ( $data, '&' );

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $u);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/x-www-form-urlencoded',
            'User-Agent: ksmobilebrowser/3.3.12572.1002 CFNetwork/758.1.6 Darwin/15.0.0',
            'Cookie: Hm_lvt_507a1673dcdcecb62f9554291e6d63fc=1435656971;',
//            'lbid: 020000000000|74f8464fe4571f88adf2a38379a2aec99b38a5c9',
            'Accept: text/html',
            'Connection: Keep-Alive'
        ));
        curl_setopt ( $ch ,  CURLOPT_POST ,  1 );
        curl_setopt ( $ch ,  CURLOPT_POSTFIELDS ,  $fields_string );

        //curl_setopt($ch, CURLOPT_COOKIE, 'QC006=5427a6abc2e76cc59a603b3925baadfe; redpoint_nav_vip=R1; redpoint_channelList=R1; QC112=7ac99ccb563c3089aa93a0e11023aa55; T00404=be57119e333614e258a0ad5b18d28dc2; QC007=https%3A%2F%2Fm.baidu.com%2Fs%3Ffrom%3D1010888o%26word%3D%25E5%25A5%2594%25E8%25B7%2591%25E5%2590%25A7%25E5%2585%2584%25E5%25BC%259F%25E7%25AC%25AC%25E4%25BA%258C%25E5%25AD%25A3');
        ob_start();//开启输出缓冲
        $r = curl_exec($ch);
        $result = ob_get_contents();//得到缓冲区输出的内容，赋给变量$phpinfo
        ob_clean();
        curl_close($ch);


        $res = CJSON::decode($result);

        if($level==1)
            $key = 'm3u8_flv';
        if($level==2)
            $key = 'm3u8';
        if($level==3)
            $key = 'm3u8_mp4';
        if($level==4)
            $key = 'm3u8_hd';
        $tvurl = @$res['data']['sources'][$key]['url'];
        $tvurl = $tvurl ? $tvurl : @$res['data']['sources']['m3u8_mp4']['url'];

        $tvurl = $tvurl ? $tvurl : @$res['data']['sources']['m3u8']['url'];
        $tvurl = $tvurl ? $tvurl : @$res['data']['sources']['m3u8_flv']['url'];
        $rm3u8 = Main::curl2($tvurl);

        return $rm3u8;

    }
    public function getSouhuM3u8($url){
        $uas = Main::userAgens();
        $k = array_rand($uas['mobile']);
        $ua = $uas['mobile'][$k];
        $u = 'http://220.181.61.213/m3u8?&start=0&end=9.8&k=hWODtfkIlBes5B6HDek2ZT8DuS9vR86iDVc2y4Nb8G6bbBXUyYbS0pbcWhoGyG2slG1HfYo7NF2tZY1S0psdyF2sWBo70ScAZMx4vmfdRDk&a=hWqbzHJUhWqFjfaptUJlzSwdoSwGoSNGopwGoSoWj9lvzSw3oSPGopw3opsGqLXdqmsWkCIv8eWM8Y2eqeWBN6wmZKACg202bTwl5esWgLxtPeClNO1GhKX3DteU0p6DDANugKbbe6kVWeyb8mx4y66S0p0cWhoVqTPcWJbsWhvsZYoAuT8cWr&sig=0Ba3bjuRClq5n4Fyc95jvAtANNeHDE90';

        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            // 'Host: 220.181.61.229',
            'Accept-Encoding: gzip, deflate',
            'bxbb: YES',
            'Accept-Language: zh-cn',
            "User-Agent: AppleCoreMedia/1.0.0.13D15 (iPhone; U; CPU OS 9_2_1 like Mac OS X; zh_cn)",
            'Accept: */*',
            'Connection: Keep-Alive'
        ));

        $response = curl_exec($ch);
        preg_match('/^Location:(.*)$/mi', $response, $matches);
        curl_close($ch);
//        var_dump($matches);die();
        return trim($matches[1]);
    }
    public static function getSohu($vurl) {
        preg_match("/v(\d+?)\.shtml/",$vurl,$arr);
        $vid = intval($arr[1]);
        $url = "http://api.tv.sohu.com/v4/video/info/$vid.json?site=1&api_key=695fe827ffeb7d74260a813025970bd5&plat=3&partner=1&sver=3.5&poid=1";
        $info = CJSON::decode(Main::curl2($url));
        $m3u8 = $info['data']['url_super'];
        $m3u8 = $m3u8 ? $m3u8 : $info['data']['url_high'];
        $m3u8 = $m3u8 ? $m3u8 : $info['data']['url_nor'];
        $m = Main::curl2($m3u8);
        $new_m3u8 = preg_replace_callback("/(http[^\#]+)/",function($macth){
            $url = $macth[1];
            $u = Main::getSouhuM3u8($url);
            return $u."\n";
        },$m);
        return $new_m3u8;

    }
    public static function m3u8ThirdParse($url) {
        require (dirname(__FILE__) . '/../extensions/parseVideo/parserVideo.class.php');
        $res = ParserVideo::parse($url);
        var_dump($res);die();
        return $res;
    }
    public static function m3u8ThirdParse2($url) {
        $out = $status = '';

        exec("node " . dirname(__FILE__) . "/parseVideojj.js $url", $out, $status);
        $res = join("", $out);
        $u = $res;
        $api = "http://videojj.com/api/videos/parse?url=$u";

        $res = CJSON::decode(Main::curl2($api));

        if (preg_match("/letv/", $url)) {
            $segs = @$res['msg']['segs'];
            $mp4 = !empty($segs['m3u8-HD']) ? $segs['HD'][0]['url'] : @$segs['HD'][0]['url'];

        }
        return $mp4;
    }
    /*
     *保存m3u8到sqlite
     *描述：把解析出来的m3u8文本保存到数据库
     *@param text $url
     *@param text $m3u8
     *
     * */
    public static function saveM3u8ToDb($url, $m3u8) {
        try {
            $old = $model = TSourceM3u8::model()->find("url=:url", array(
                'url' => $url
            ));
            if (!$model) $model = new TSourceM3u8;
            $model->url = $url;
            $model->m3u8 = $m3u8;
            if (!$old) $model->add_time = date('Y-m-d H:i:s');
            $model->update_time = date('Y-m-d H:i:s');
            $model->save();
        }
        catch(Exception $e) {
            var_dump($e);
        }
    }
    public static function toData($status = 1) {
        if ($status) $res['status'] = array(
            'errorcode' => 'Ok',
            "errorinfo" => ""
        );
        else $res['status'] = array(
            'errorcode' => 'Error',
            "errorinfo" => "some error"
        );
        $res['data'] = array();
        return $res;
    }
    //       $hanziarr = array("一","二","三","四","五","六","七","八","九","十","十一","十二","十三","十四","十五","十六","十七","十八","十九","二十","二十一","二十二","二十三","二十四","二十五","二十六","二十七","二十八","二十九","三十",
    //"三十一","三十二","三十三","三十四","三十五","三十六","三十七","三十八","三十九","四十","四十一","四十二","四十三","四十四","四十五","四十六","四十七","四十八","四十九","五十","五十一","五十二","五十三","五十四","五十五","五十六","五十七",
    //"五十八","五十九","六十","六十一","六十二","六十三","六十四","六十五","六十六","六十七","六十八","六十九","七十","七十一","七十二","七十三","七十四","七十五","七十六","七十七","七十八","七十九","八十","八十一","八十二","八十三","八十四",
    //"八十五","八十六","八十七","八十八","八十九","九十","九十一","九十二","九十三","九十四","九十五","九十六","九十七","九十八","九十九","一百");
    /*
     * 汉字数组转为阿拉伯数字
     * @param string $str
     * @param int $replace 1--数字换汉字 2--汉字换数字
     *
     * return string
     * */
    public static function han2num($str, $ext = '', $ext2 = '季',$replace=0) {
        $numarr = array(
            1,
            2,
            3,
            4,
            5,
            6,
            7,
            8,
            9,
            10,
            11,
            12,
            13,
            14,
            15,
            16,
            17,
            18,
            19,
            20
        );
        $hanziarr = array(
            "一",
            "二",
            "三",
            "四",
            "五",
            "六",
            "七",
            "八",
            "九",
            "十",
            "十一",
            "十二",
            "十三",
            "十四",
            "十五",
            "十六","十七","十八","十九","二十"
        );
        if($replace==1)
        {

            foreach ($numarr as $k => $v) {
                if ($v==$str) {
                    return   preg_replace("/(" . $v . ")/", $ext . $hanziarr[$k], $str);

                }
            }
        }
        foreach ($hanziarr as $k => $v) {
            $v = $ext . $v . $ext2;
            if (preg_match("/(" . $v . ")/", $str)) {
                $num = $ext . $numarr[$k];
                $str = preg_replace("/(" . $v . ")/", $num, $str) . $ext2;
            }
        }
        return $str;
    }
    /*
     * 取得缓存中的token sn
     *
     * */
    public static function getSnToken() {
        $wx = Yii::app()->session['wxInfo'];
        $openid = $wx['openid'];
        return Yii::app()->session['sn_' . $openid];
    }
    /*
     * 下载远程图片并压缩
     * @param string $url
     * */
    public function getImage($url) {
        $info = pathinfo($url);
        $new_dir = UPLOAD_PATH . date('Ymd') . '/';
        if (!file_exists($new_dir)) Main::mkdirs($new_dir);

        $filename =  $new_dir.md5($url) . "." . $info['extension'];
//        $filenameold = UPLOAD_PATH .md5($url) . "." . $info['extension'];

        if (file_exists($filename) ) {
            $size = @getimagesize($filename);
            $newWidth = 300;
            $width = $size[0];
            $height = $size[1];
            if ($width > 500) {
                $h = $newWidth * $height / $width;
                $filename = Main::resizeImage($filename, array(
                    $newWidth,
                    $h
                ));
            }
            return Main::imageUrl($filename);
        }
        $curl = curl_init($url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $imageData = curl_exec($curl);

        curl_close($curl);
        file_put_contents($filename,$imageData);


        //      return Main::imageUrl(Main::resizeImage($filename,0.8));
        return Main::imageUrl($filename);
    }
    /*
     * 取得微信openid
     * */
    public static function getWxUserInfo() {
//        $arr['openid'] = 'ohzhQtzexnHhTkP00LqIpNlEJjIc';
//        Yii::app()->session['wxInfo'] = $arr;
//        return;
        $rs = urlencode('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
        $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx275b2d975956c77e&redirect_uri=$rs&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect";
        if (!empty($_GET['code'])) {
            $code = $_GET['code'];
            $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx275b2d975956c77e&secret=dfd4971dfe49391c71e16def371e3e89&code=$code&grant_type=authorization_code";
            $res = Main::curl2($url);
            Yii::app()->session['wxInfo'] = @CJSON::decode($res);
            return;
            $res = json_decode($res);
            $ACCESS_TOKEN = $res->access_token;
            $OPENID = $res->openid;
            $url = "https://api.weixin.qq.com/sns/userinfo?access_token=$ACCESS_TOKEN&openid=$OPENID&lang=zh_CN";
            $r = file_get_contents($url);
            Yii::app()->session['wxInfo'] = @CJSON::decode($r);;
        } else { //file_get_contents($url);
            header("LOCATION: $url");
            exit();
        }
    }
    /**
     * 把数组中的某些值变为key，和value
     * @param array $arr
     * @param string   $key
     * @param string $val
     *
     */

    public static function arrayKeyValue($arr,$key,$val){
        $new = array();
        foreach($arr as $k=>$v)
        {

            if(is_object($v))
            {
                $v = @((array)$v->attributes());
                $v = @$v['@attributes'];

            }

            $new[$v[$key]] = $v[$val];

        }
        return $new;
    }

    /**
     * @param $string
     * @return string
     */
    function String2Hex($string){
        $hex='';
        for ($i=0; $i < strlen($string); $i++){
            $hex .= dechex(ord($string[$i]));
        }
        return $hex;
    }

    /**
     * @param $hex
     * @return string
     */
    function Hex2String($hex){
        $string='';
        for ($i=0; $i < strlen($hex)-1; $i+=2){
            $string .= chr(hexdec($hex[$i].$hex[$i+1]));
        }
        return $string;
    }

    /**
     * @param $data
     * @return string
     */
    public function decryKey($pws){

        $private = '-----BEGIN RSA PRIVATE KEY-----
MIICXgIBAAKBgQDi7SpFLpsAtn17R8yQrEI1d+Y7wfMnosfDzLGl9d2mkPB715/T
AOEh+SYNz5luMecntldXQyAmRQ2nafl/evjhw7P4lvH7rGlO6EPvepZDuawdyjFA
/TDyZrT7LGfk41felDU2nLzMx+uX35Q2NzopYJpGzK376Ny+pJYV1XUiDwIDAQAB
AoGBAL/v6bjqWqCXujrz18rmaHnhGBOjUI9N17l9ASVmeDvSjBWzo7NNIx8hJVa5
KQVToDiuueFNHXxBG/NmZ2m0EZ0LtrrS7CrQbvyPBi+z7iv5KRVAT1IUIU0eAWMP
8gUkKQCJYxOvf4lA2U6xqYM4SC5GE/Ht14qq4HhjVYrbAq4BAkEA8hvjl4oLs4FX
6OItZirIvBT5Uo7iNrnZQQfVcx4fE+0LgYvQNAgH34XI5Cm42LT49LBNxWLg+vHJ
/6A9OS+iLwJBAO/yRj1CMFkkfx3QFdOzMYH7a/OkNNzD3doN8P7VlyfWia/QZEqL
DbCiVBXeVJKGV1V6NehTYPfXgcLb/f9V5iECQQC2IR7L//AfgFy2d3c5lVPekVSh
s5UfIB38Gr2K1Q0B+1+de6ULj0ME9mqSoYRJmZJy2DIZG/ItNTkFEPEdlOTHAkBj
Yl03eFfgRF6mcY7o3bru1L2079m5ayNT8xxT4RI3vQPQn6c6vPfRpprfZ/RtsFky
HWmArjBm14t2s3o0LVchAkEA0RjHhvc0rJdA1Rt0QxVD+sEo8BhVOWpaggnI1gIU
qtG1DeMIDJE/nVfA6yxP58UlyCHYtjMycIw9R4FIhNINrQ==
-----END RSA PRIVATE KEY-----';
        if (!$privateKey = openssl_pkey_get_private($private)) return false;

        //Decrypt
        $decrypted_text = "";
        if (!openssl_private_decrypt(base64_decode($pws), $decrypted_text, $privateKey)) return false;

        //Decrypted :)

        //Free key
        openssl_free_key($privateKey);
        return $decrypted_text;
    }




}


